package com.taomeishu.mailcrazy.checkers;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.taomeishu.mailcrazy.AbstractMailExistChecker;
import com.taomeishu.mailcrazy.CheckResult;
import com.taomeishu.mailcrazy.Mail;
import com.taomeishu.mailcrazy.http.ClientResponse;
import com.taomeishu.mailcrazy.parser.ResultParseException;
import com.taomeishu.mailcrazy.parser.ResultParser;

public class TomMailExistChecker extends AbstractMailExistChecker {

	private TomResultParser tomResultParser = new TomResultParser();
	
	@Override
	protected String makeRequestUrl(String username, String domainName) {
		return "http://bjcgi.tom.com/cgi-bin/getorgid.cgi";
	}

	@Override
	protected ResultParser getResultParser() {
		return tomResultParser;
	}

	@Override
	protected String getReferer() {
		return "http://bjcgi.tom.com/cgi-bin/tom_reg.cgi?rf=060704";
	}

	@Override
	protected boolean usePostMethod() {
		return true;
	}

	@Override
	protected byte[] getPostData(String username, String domainName) {
		String s = "funcid=reguser&rf=060704&refer=&year=1980&month=1&day=1&argee=1&idnum=4401&question=%CE%D2%D7%EE%B0%AE%B5%C4%C8%CB%B5%C4%C3%FB%D7%D6&answer=tomtommail&uid="+ 
				username +"&hid_pwd=&password=&hid_pwdcfm=&confirm_password=&safemail=&authcode=&argee_c=yes";
		return s.getBytes();
	}
	
	static class TomResultParser implements ResultParser {

		@Override
		public CheckResult parse(ClientResponse clientResponse, String username, String domainName) throws ResultParseException {
			byte[] data = clientResponse.getData();
			CheckResult result = new CheckResult(true);
			Mail mail = new Mail(username, domainName);
			result.setMail(mail);
			try {
				Document doc = Jsoup.parse(new ByteArrayInputStream(data), "gb2312", "http://bjcgi.tom.com/cgi-bin/");
				String userInfo = doc.getElementById("userInfo").text();
				if (userInfo.contains("已经")) {
					// exist
					result.addExistMail(mail);
				} else {
					result.addNotExistMail(mail);
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			return result;
		}
		
	}

}
